package simpledb.GUI;

import com.trolltech.qt.gui.*;
import java.io.*;
import java.sql.*;

import simpledb.opt.HeuristicQueryPlanner;
import simpledb.remote.SimpleDriver;


public class QueryWindow extends QWidget
{

	private static Connection conn = null;

	QLineEdit queryLineEdit;
	QPushButton submitQueryButton;
	QTextEdit queryOutputTextArea;
	QTextEdit queryLogArea;
//	FileInputStream fin;
//	FileInputStream opt;


	public QueryWindow()
	{
    	queryLineEdit = new QLineEdit(this);
    	queryLineEdit.setFixedHeight(25);

    	submitQueryButton = new QPushButton("Execute Query", this);
    	submitQueryButton.clicked.connect(this, "on_executeQueryButton_clicked()");

    	queryOutputTextArea = new QTextEdit("<b>Output:</b>", this);
    	queryOutputTextArea.append("\n");
    	queryOutputTextArea.setReadOnly(true);

    	queryLogArea = new QTextEdit("<b>Log:</b", this);
    	queryLogArea.append("\n");
    	queryLogArea.setReadOnly(true);

    	QVBoxLayout layout = new QVBoxLayout();
    	layout.addWidget(queryLineEdit);
    	layout.addWidget(submitQueryButton);
    	layout.addWidget(queryOutputTextArea);
    	layout.addWidget(queryLogArea);
    	setLayout(layout);
	}

	public void on_executeQueryButton_clicked()
	{
		doQuery(queryLineEdit.text());
		queryLineEdit.clear();
	}

	public void doQuery(String cmd)
	{
		System.out.println("ENTERED");
		try {
			System.out.println("ENTERED");
		    Statement stmt = conn.createStatement();
		    System.out.println("ENTERED");
		    ResultSet rs = stmt.executeQuery(cmd);
		    System.out.println("ENTERED");
		    ResultSetMetaData md = rs.getMetaData();
		    int numcols = md.getColumnCount();
		    int totalwidth = 0;

		    System.out.println("ENTERED");
		    // print header
		    String header = "";
		    for(int i=1; i<=numcols; i++) {
				int width = md.getColumnDisplaySize(i);
				totalwidth += width;
				String fmt = "%" + width + "s";
				header += String.format(fmt, md.getColumnName(i));
			}
		    queryOutputTextArea.append(header);

			String dashes = "";
			for(int i=0; i<totalwidth; i++)
			{
				dashes += "-";
			}
			queryOutputTextArea.append(dashes);

		    // print records
		    while(rs.next()) {
		    	String row = "";
				for (int i=1; i<=numcols; i++) {
					String fldname = md.getColumnName(i);
					int fldtype = md.getColumnType(i);
					String fmt = "%" + md.getColumnDisplaySize(i);
					if (fldtype == Types.INTEGER)
						row += String.format(fmt + "d", rs.getInt(fldname));
					else
						row += String.format(fmt + "s", rs.getString(fldname));
				
				}
				queryOutputTextArea.append(row);
			}

		    System.out.println("WILL CLOSE");
			rs.close();

			//Finally get the log.
			System.out.println("OUT");
			getLog();
			System.out.println("got log");
			drawTree();
		}
		catch (SQLException e)
		{
			queryOutputTextArea.append("SQL Exception: " + e.getMessage() + "\n");
			e.printStackTrace();
		}
	}

	public void drawTree()
	{
		String optType = "Basic";
	    try {
	        BufferedReader input =  new BufferedReader(new FileReader("opt"));
	        try {
	          String line = null;
	          while ((line = input.readLine()) != null)
	          {
	            optType = (String)line;
	          }
	        }
	        finally {
	          input.close();
	        }
	      }
	      catch (IOException ex){
	        ex.printStackTrace();
	      }
	      if(optType.startsWith("HeuristicQueryPlanner"))
	      {
	    	  System.out.println("IT'S A DAMN");
	    	  TreeWindowHeuristic tree1 = new TreeWindowHeuristic();
	    	  tree1.show();
	      }
	      else
	      {
	    	  TreeWindow tree = new TreeWindow();
	    	  tree.show();
	      }
	}

	public void getLog()
	{
		queryLogArea.clear();
		queryLogArea.append("<b>Log:</b");

	    try {
	        BufferedReader input =  new BufferedReader(new FileReader("lastQueryLog"));
	        try {
	          String line = null;
	          while ((line = input.readLine()) != null)
	          {
	            queryLogArea.append(line);
	          }
	        }
	        finally {
	          input.close();
	        }
	      }
	      catch (IOException ex){
	        ex.printStackTrace();
	      }
	}

    public static void main(String[] args) throws SQLException
    {
    	QApplication.initialize(args);

		Driver d = new SimpleDriver();
		conn = d.connect("jdbc:simpledb://localhost", null);

    	QueryWindow window = new QueryWindow();
    	window.show();
    	QApplication.exec();
    }

}
